﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Qu.SeniorProject.Model;
using System.IO;

namespace Qu.SeniorProject.WebUI.Controllers
{
    public class DocumentController : Controller
    {
        private UserInfo GetUserInfo()
        {
            var userInfo = Session["UserInfo"] as UserInfo;
            if (Request.IsAuthenticated && userInfo == null)
            {
                //Store the User Info in a Session
                userInfo = UserRepository.GetUserInfo(User.Identity.Name);

                if (userInfo != null)
                    Session["UserInfo"] = userInfo;
            }
            return userInfo;
        }

        public ActionResult Index(string id)
        {
            var userInfo = GetUserInfo();

            if (userInfo == null)
                return RedirectToAction("LogOn", "Account");

            if (!string.IsNullOrEmpty(id))
            {
                if (id.StartsWith("pd"))
                {
                    id = id.Remove(0, 2);
                    //Request Template and Guides
                    var docInfo = DocumentRepository.GetProjectDocument(int.Parse(id));
                    var filePath = string.Empty;

                    if (docInfo != null)
                        return File(Path.Combine(Server.MapPath("~/"), docInfo.DocumentPath), string.Format("application/{0}", docInfo.DocumentExtension), docInfo.DocumentName);
                    else 
                        return RedirectToAction("Index", "Home");
                }
                else
                {
                    //Request Template and Guides
                    var docInfo = DocumentRepository.Get(int.Parse(id));
                    var filePath = string.Empty;

                    if (docInfo != null)
                        return File(Path.Combine(Server.MapPath("~/App_Data"), docInfo.Path, docInfo.FileName), string.Format("application/{0}", docInfo.Extension), docInfo.FileName);
                }
            }

            ViewBag.Major = userInfo.Major;

            var documents = DocumentRepository.GetAll();
            return View(documents);
        }

    }
}
